import { ReqPage } from "@/api/interface";
import { Applet } from "@/api/interface/iot";
import { serviceStart, serviceStop } from "@/api/modules/service/service";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import MachineSelect from "@/components/Sansan/GatewayDialog/machineSelect";
import OnlineStatus from "@/components/Sansan/Status/OnlineStatus";
import { MessageType } from "@/enums/messageEnum";
import { RouterPath } from "@/enums/routerPath";
import { ServiceStatusTypes, SvcType } from "@/enums/statusEnum";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import router from "@/routers";
import { AuthBtns } from "@/utils/constants";
import { getDictObj } from "@/utils/cacheUtil";
import { dataFormat } from "@/utils/format";
import { confirm, showMsg, showTips } from "@/utils/util";
import LoggerDialog from "@/views/system/services/components/loggerDialog";
import { ComponentInternalInstance, getCurrentInstance, PropType } from "vue";
import { useRoute } from "vue-router";
import { addAppletInstance, delAppletInstance, findAppletInstanceList } from "@/api/modules/applet/userApplet";
import PublicTag from "@/components/Sansan/Status/PublicTag";
import mittBus from "@/utils/mittBus";
export default defineComponent({
	props: {
		detail: {
			type: Object as PropType<Applet.ResUserApplet>,
			default: () => {}
		}
	},
	emits: ["change"],
	setup(props) {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const route = useRoute();
		const readonly = ref(false);

		// const btnList = ref<any>([
		// 	{ menuName: "添加设备", path: "changeNode", btnClass: "primary" },
		// 	{ menuName: "删除", path: "del" },
		// 	{ menuName: "启动", path: "restart" },
		// 	{ menuName: "停止", path: "stop" },
		// 	{ menuName: "发布端应用", path: "deploy" },
		// 	{ menuName: "撤销发布", path: "undeploy" }
		// ]);
		const btnList = ref<any[]>([]);
		useAuthButtons(AuthBtns.appletDevelop).then((res: any) => {
			btnList.value = res.filter(
				(item: any) => item.btnGroup == "7" && item.component != "publish" && item.component != "unpublish"
			);
			readonly.value = btnList.value.find((item: any) => item.path == "mod") ? false : true;
		});
		// const nodeState = reactive<any>({ list: [], val: {} });
		const initParam = reactive<ReqPage>({
			pageIndex: 0,
			pageSize: 20,
			appId: props.detail.id,
			nodes: ""
		});

		const dataCallback = (data: any) => {
			return {
				datalist: data.records,
				total: data.total || 0,
				pageIndex: data.current,
				pageSize: data.size
			};
		};

		const getTableList = async (params: any) => {
			return findAppletInstanceList({ ...params, key: props.detail.key });
		};

		// const initNode = async () => {
		// 	const { result, code } = await findAppletInstanceList({ key: props.detail.key });
		// 	if (code == 200 && result.records.length) {
		// 		nodeState.list = result.records;
		// 		nodeState.val = nodeState.list[0];
		// 		changeNode();
		// 	} else {
		// 		nodeState.list = [];
		// 		nodeState.val = {};
		// 	}
		// };
		// const changeNode = () => {
		// 	initParam.nodes = nodeState.val.sn;
		// 	proTable.value.reset();
		// };
		const serviceStatusLabels = ref<any>({});
		onMounted(async () => {
			// initNode();
			serviceStatusLabels.value = await getDictObj("service_status");
		});
		const proTable = ref<any>();

		const delNode = async (dataList: any[]) => {
			confirm({ content: "删除节点后无法找回，确定进行当前操作" }).then(async flag => {
				if (!flag) {
					return;
				}
				let { code, message } = await delAppletInstance({
					// nodeSn: dataList.map(item => item.nodeSn).join(","),
					// appKey: route.query.key
					id: dataList.map(item => item.id).join(",")
				});
				let ok = showTips(code, `删除节点`, message);
				if (ok) {
					// initNode();
					proTable.value.reset();
				}
			});
		};
		const start = async (data: any) => {
			if (!data[0]) {
				showMsg("请选择要操作的服务", MessageType.warning);
				return;
			}
			setTimeout(async () => {
				let { code, message } = await serviceStart({ id: data[0].id });
				showTips(code, "服务启动", message) && proTable.value.getTableList();
			}, 1000);
		};
		const stop = async (data: any) => {
			if (!data[0]) {
				showMsg("请选择要操作的服务", MessageType.warning);
				return;
			}
			setTimeout(async () => {
				let { code, message } = await serviceStop({ id: data[0].id });
				showTips(code, "服务停止", message) && proTable.value.getTableList();
			}, 1000);
		};
		const clickBtn = async (fn: string, scope: any) => {
			let selectList = scope?.row ? [scope?.row] : scope?.selectList || [];
			switch (fn) {
				case "add":
				case "changeNode":
					drawerVisible.value = true;
					break;
				case "del":
					delNode(selectList);
					break;
				case "detail":
					router.push({
						path: RouterPath.appletDeployDetail,
						query: { nodeSn: selectList[0].nodeSn, appId: selectList[0].id, key: selectList[0].appKey }
					});
					break;
				case "logger":
					if (selectList && selectList.length != 1) {
						showMsg("请选择一个服务查看日志。", MessageType.warning);
						return;
					}
					let info = { ...(selectList && selectList[0]) };
					loggerDialog.title = "【" + info.name + "】运行日志";
					loggerDialog.detail = info;
					loggerDialog.visible = true;
					break;
				case "stop":
					stop(selectList);
					break;
				case "start":
					start(selectList);
					break;
			}
		};
		const submitAddNode = async (val: any) => {
			if (!val.length) return;
			const res = await addAppletInstance({ nodeSn: val[0].sn, appKey: route.query.key });
			let ok = showTips(res.code, "添加服务", res.message);
			if (ok) {
				// initNode();
				proTable.value.reset();
			}
		};
		// 表格配置项
		const columns: ColumnProps[] = [
			{ type: "selection", fixed: "left", width: "auto" },
			// { prop: "deviceStatus", label: "设备状态", width: "130px" },
			{ prop: "nodeSn", label: proxy?.$t("applet_deploy.tablist_label.name"), width: "180px" },
			{ prop: "appInstanceId", label: proxy?.$t("applet_deploy.tablist_label.app_instance") },
			{ prop: "system", label: proxy?.$t("applet_deploy.tablist_label.system"), width: "100px" },
			{ prop: "ip", label: "IP", width: "150px" },
			// { prop: "extend", label: "继承应用配置", width: "120px" },
			{ prop: "status", label: proxy?.$t("applet_deploy.tablist_label.status"), width: "100px" },
			{ prop: "updateTime", label: proxy?.$t("applet_deploy.tablist_label.update_time"), width: "180px" },
			{ prop: "version", label: proxy?.$t("applet_deploy.tablist_label.version"), width: "100px" },
			{ prop: "marketPublish", label: proxy?.$t("applet_deploy.tablist_label.market_publish"), width: "70px" },
			{ prop: "operate", label: proxy?.$t("applet_deploy.tablist_label.operate"), fixed: "right", width: "130" }
		];
		const loggerDialog = reactive<any>({
			detail: {},
			title: proxy?.$t("applet_deploy.dialog_title.logger"),
			visible: false
		});
		const options = ref(SvcType);
		const drawerVisible = ref(false);
		onBeforeMount(() => {
			mittBus.on("refreshAppletDetail", () => {
				proTable.value.reset();
			});
		});
		onBeforeUnmount(() => {
			mittBus.off("refreshAppletDetail");
		});
		return () => {
			return (
				<div class="">
					<MachineSelect v-model:visible={drawerVisible.value} onSubmit={submitAddNode}></MachineSelect>
					<LoggerDialog
						width="1024px"
						title={loggerDialog.title}
						v-model:visible={loggerDialog.visible}
						detail={loggerDialog.detail}
						footerLabel={["关闭"]}
					/>
					<ProTable
						ref={proTable}
						title={btnList.value.length ? "" : proxy?.$t("applet_deploy.tab_title.node")}
						columns={columns}
						requestApi={getTableList}
						initParam={initParam}
						dataCallback={dataCallback}
					>
						{{
							tableHeader: (scope: any) => {
								return btnList.value
									?.filter((item: any) => item.path != "del")
									.map((item: any) => {
										return (
											<el-button onClick={() => clickBtn(item.path, scope)} type={item.btnClass}>
												{item.menuName}
											</el-button>
										);
									});
							},
							appInstanceId: (scope: any) => {
								return (
									<div class="truncate cursor-pointer primary-color" onClick={() => clickBtn("detail", scope)}>
										{scope.row.appInstanceId}
									</div>
								);
							},
							marketPublish: (scope: any) => {
								return scope.row.extend ? (
									<PublicTag
										v-model={scope.row.marketPublish}
										types={{ yes: "success", no: "danger" }}
										labels={{ yes: "是", no: "否" }}
									/>
								) : (
									""
								);
							},
							// extend: (scope: any) => {
							// 	return scope.row.extend ? (
							// 		<PublicTag
							// 			v-model={scope.row.extend}
							// 			types={{ yes: "success", no: "danger" }}
							// 			labels={{ yes: "是", no: "否" }}
							// 		/>
							// 	) : (
							// 		""
							// 	);
							// },
							status: (scope: any) => {
								return (
									<OnlineStatus
										labels={serviceStatusLabels.value}
										onlineLabel={proxy?.$t("applet_deploy.status.online")}
										offlineLabel={proxy?.$t("applet_deploy.status.offline")}
										types={ServiceStatusTypes}
										v-model={scope.row.status}
									></OnlineStatus>
								);
							},
							svcType: (scope: any) => {
								return scope.row.svcType && options.value.filter((item: any) => item.value == scope.row.svcType)[0].label;
							},
							createTime: (scope: any) => {
								return dataFormat("datetime", scope.row.createTime);
							},
							updateTime: (scope: any) => {
								return dataFormat("datetime", scope.row.updateTime);
							},
							startTime: (scope: any) => {
								return dataFormat("datetime", scope.row.startTime);
							},
							operate: (scope: any) => {
								return (
									<>
										{btnList.value.map((item: any) => {
											return item.path == "del" ? (
												<el-link type="danger" link class="iconfont icontrash-2" onClick={() => clickBtn(item.path, scope)}>
													{proxy?.$t("applet_deploy.link.delete")}
												</el-link>
											) : (
												""
											);
										})}
										<el-link type="primary" link class="iconfont iconbx-file" onClick={() => clickBtn("detail", scope)}>
											{proxy?.$t("applet_deploy.link.detail")}
										</el-link>
									</>
								);
							}
						}}
					</ProTable>
				</div>
			);
		};
	}
});
